package com.itheima.fliter;


import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
//@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        log.info("拦截到请求:{}",requestURI);

        String[] urls = {
                "/favicon.ico",
                "/frame/**"
        };

        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match){
                System.out.println("被放行");
                filterChain.doFilter(request,response);
                return;
            }
        }
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
//        String userId = redisTemplate.opsForValue().get("userId");
        if(userId == null){

            return;
        }

       if(userId != null){
            BaseContext.threadLocal.set(userId);
        }
        filterChain.doFilter(request,response);
        return;
    }
}
